import { useEffect, useState } from 'react'
import { SelectInput } from 'tdesign-react'
import styles from './index.module.less'
import { SearchIcon } from 'tdesign-icons-react'

type PropsType = {
  onChange?: (e: any) => void
  options: SelectOptionListType
}

const InputSearch = (props: PropsType) => {

  const {
    onChange = () => { },
    options
  } = props

  const [selectedValue, setSelectedValue] = useState<object>({ label: '', value: '' })
  const [positionPopupVisible, setPositionPopupVisible] = useState<boolean>(false)
  const [searchValue, setSearchValue] = useState<string>('')

  const onPositionInputChange = (keyword: string) => {
    setSearchValue(keyword)
  }

  const getDisplayOptions = () => {
    return options.filter((item: any) => item.label?.includes(searchValue))
  }

  const displayOptions = getDisplayOptions()

  const onPositionOptionClick = (e: any) => {
    setSelectedValue(e)
    setPositionPopupVisible(false)
    onChange(e)
  }

  const onPositionPopupVisibleChange = (e: boolean) => {
    setPositionPopupVisible(e)
  }

  return <div>
    <SelectInput
      value={selectedValue}
      popupVisible={positionPopupVisible}
      placeholder="请输入任意关键词"
      allowInput
      clearable
      style={{ width: '300px' }}
      onInputChange={onPositionInputChange}
      onPopupVisibleChange={onPositionPopupVisibleChange}
      panel={
        <ul className={styles.optionUl}>
          {displayOptions?.map((item: any, index: number) => (
            <li key={index} onClick={() => onPositionOptionClick(item)} className={styles.optionLi}>
              {item.label}
            </li>
          ))}
        </ul>
      }
      suffixIcon={<SearchIcon />}
    />
  </div>

}

export default InputSearch